package com.tuanbiao.dialog;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatTextView;

import com.abiao.lib_utils.StringUtils;
import com.hzjq.data.entity.SettingParams;
import com.hzjq.data.entity.UIDRule;
import com.hzjq.data.hzjq.entity.CapRecordEntity;
import com.hzjq.lib.BlastKool;
import com.jakewharton.rxbinding4.view.RxView;
import com.tuanbiao.R;
import com.tuanbiao.base.action.ToastAction;
import com.tuanbiao.models.action.DetonatorAction;
import com.tuanbiao.ui.CaptureActivity;
import com.tuanbiao.utils.ClickUtil;
import com.tuanbiao.utils.MediaUtils;
import com.tuanbiao.utils.Utils;
import com.tuanbiao.widget.ClearEditText;

import java.util.concurrent.TimeUnit;

import timber.log.Timber;

/**
 * @author abiao
 * @date 2022/9/9 9:40
 * @description:
 */
public class InsertDetonatorDialog extends BaseDialogFragment implements ToastAction , DetonatorAction {
    private AppCompatTextView tvTitle;
    private ClearEditText etUid;
    private ImageView ivScan;
    private AppCompatEditText etDelay;
    private AppCompatEditText etRow;
    private AppCompatEditText etColumn;
    private AppCompatButton btnCancel;
    private AppCompatButton btnConfirm;
    private LinearLayout llRowDelay;
    private OnConfirmListener listener;
    private long mMaxDelay;
    private static final String KEY_MAX_DELAY = "_KEY_MAX_DELAY_";

    public InsertDetonatorDialog setListener(OnConfirmListener listener) {
        this.listener = listener;
        return this;
    }

    private ActivityResultLauncher<Intent> launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult()
            , result -> {
                if (result.getResultCode() == Activity.RESULT_OK ) {
                    if (result.getData() != null) etUid.setText(result.getData().getStringExtra(Utils.BAR_CODE));
                } else {
                    showShort("相机打开出错，请稍后重试");
                }
            });

    public static InsertDetonatorDialog newInstance(long maxDelay) {
        Timber.i("newInstance:"+maxDelay);
        InsertDetonatorDialog fragment = new InsertDetonatorDialog();
        Bundle args = new Bundle();
        args.putLong(KEY_MAX_DELAY, maxDelay);
        fragment.setArguments(args);
        return fragment;
    }
    @Override
    protected int getLayoutId() {
        return R.layout.dialog_detonator_insert;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mMaxDelay = getArguments().getLong(KEY_MAX_DELAY);
        Timber.i("onCreate:"+mMaxDelay);
    }

    @Override
    protected void initViews(View view) {
        Timber.i("initViews:"+mMaxDelay);
        SettingParams settings = BlastKool.Companion.loader().quick().getSettings();
        etUid = (ClearEditText) view.findViewById(R.id.et_uid);
        ivScan = (ImageView) view.findViewById(R.id.iv_scan);
        etDelay = (AppCompatEditText) view.findViewById(R.id.et_delay);
        etRow = (AppCompatEditText) view.findViewById(R.id.et_row);
        etColumn = (AppCompatEditText) view.findViewById(R.id.et_column);
        btnCancel = (AppCompatButton) view.findViewById(R.id.btn_cancel);
        btnConfirm = (AppCompatButton) view.findViewById(R.id.btn_confirm);
        llRowDelay = view.findViewById(R.id.ll_row_delay);
        etUid.setFilters(new InputFilter[] { new InputFilter.LengthFilter(settings.getUidRule() == UIDRule.QH214? 27 : 13) });
        boolean show = mMaxDelay == 0;
        if (mMaxDelay == 0) {
            llRowDelay.setVisibility(View.GONE);
        } else {
            llRowDelay.setVisibility(View.VISIBLE);
        }
        RxView.clicks(ivScan)
                .throttleFirst(3000, TimeUnit.MICROSECONDS)
                .subscribe(unit -> launcher.launch(CaptureActivity.createIntent(InsertDetonatorDialog.this)));

        btnCancel.setOnClickListener(v -> {
            if (null != listener) listener.onCancel();
            dismiss();
        });

        btnConfirm.setOnClickListener(v -> {
            if (ClickUtil.isFastClick()) {
                return;
            }
            String uid = getString(etUid);
            String delay = getString(etDelay);
            String row = getString(etRow);
            String column = getString(etColumn);
            if (TextUtils.isEmpty(uid)) {
                showShort("请输入雷管编码");
                return;
            }
            if(settings.getUidRule() == UIDRule.QH214){
                boolean b = uid.length() == 13 || uid.length() == 27;
                if (!b) {
                    showShort("请输入13或27位雷管编码");
                    return;
                }
            } else {
                if (uid.length() != 13) {
                    showShort("请输入13位雷管编码");
                    return;
                }
            }
            if (StringUtils.isContainChinese(uid)) {
                showShort("编码不能包含汉字");
                return;
            }
            if (mMaxDelay != 0) {
                if (TextUtils.isEmpty(delay)) {
                    showShort("请输入延时");
                    return;
                }
                if (Long.parseLong(delay) > mMaxDelay) {
                    showShort("延时不能大于" + mMaxDelay);
                    return;
                }
                if (TextUtils.isEmpty(row)) {
                    showShort("请输入排号");
                    return;
                }
                if (Integer.parseInt(row) > 999) {
                    showShort("排号最大值999");
                    return;
                }
                if (TextUtils.isEmpty(column)) {
                    showShort("请输入孔号");
                    return;
                }
                if (Integer.parseInt(column) > 99999) {
                    showShort("排号最大值99999");
                    return;
                }
            }

            if (!isCorrectCapByUidRule(uid)) {
                showShort("编码错误");
                MediaUtils.playSound(R.raw.code_error);
                return;
            }


            if (null != listener) listener.onConfirm(this,uid, delay, row, column,settings.getUidRule());
            dismiss();
        });
    }

    public interface OnConfirmListener {
        void onConfirm(BaseDialogFragment dialogFragment,String uid, String delay, String row, String column,UIDRule rule);

        void onCancel();
    }
}
